package com.superatom.concurrent.basic.lock;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.LockSupport;

/**
 * 自己实现锁功能，更好理解锁概念
 */
public class SuperAtomLock implements Lock {
    // 标记，记录是否有人拿了锁
    AtomicReference<Thread> owner = new AtomicReference<>();
    // 存储等待的线程的信息
    LinkedBlockingQueue<Thread> waiters = new LinkedBlockingQueue<>();


    /**
     * 锁上，如果获取不了锁，一直等待
     */
    @Override
    public void lock() {
        boolean park = false;
        while (!tryLock()){
            if (!park){
                // 加入等待集合
                waiters.offer(Thread.currentThread());
                park = true;
            }else{
                // 进入等待
                LockSupport.park();
            }
        }

        waiters.remove(Thread.currentThread());
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {

    }

    /**
     * 尝试拿锁
     * @return
     */
    @Override
    public boolean tryLock() {
        // 直接内存操作
        return owner.compareAndSet(null, Thread.currentThread());
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return false;
    }

    @Override
    public void unlock() {
        // 释放锁，成功后通知所有等待者
        if (owner.compareAndSet(Thread.currentThread(), null)){
             Thread next = null;
             while ((next = waiters.peek()) != null){
                 LockSupport.unpark(next);
             }
        }
    }

    @Override
    public Condition newCondition() {
        return null;
    }
}
